<template>

    <!--数字键盘-->
    <div>
        <el-dialog class="count-keyboard-dialog" :class="[{ nopoint: !isShowPoint }]" width="600px" v-model="visible"
            :title="title" @opened="dialogOpened">
            <el-input v-model="inputVal" :placeholder="placeholder" ize="large" style="margin-bottom:10px" />
            <div id="count-keyboard" :class="[keyboardContainerClass]" :data-class="isShowPoint ? '' : 'nopoint'">
            </div>
            <template #footer>
                <div class="dialog-footer">

                    <el-button type="primary" style="width: 100%;height: 61px;line-height: 61px;" size="large"
                        @click="confirmInput">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>


    </div>


</template>
<script setup lang='ts'>
// @ts-nocheck

import { ref, watch, nextTick, onBeforeUnmount } from 'vue'

import Keyboard from 'simple-keyboard'
import 'simple-keyboard/build/css/index.css'
import { ElMessage } from 'element-plus'

const props = withDefaults(defineProps<{ modelValue: boolean, title?: string, isShowPoint?: boolean, placeholder?: string, keyboardContainerClass: string, layout?: any }>(), {
    title: '请输入', isShowPoint: true, placeholder: '请输入'

})

const emit = defineEmits(['onChange', 'onKeyPress', 'update:modelValue', 'onConfirm'])
const visible = ref(props.modelValue)
const inputVal = ref('')
let keyboard: any = null
let isInit = true  //是否第一次初始化，只在第一次初始化键盘实例
function setKeyboardInput(val) {
    keyboard && keyboard.setInput(val)
}
defineExpose({ setKeyboardInput })

function dialogOpened() { //Dialog 打开动画结束时的回调
    initKeyboard(isInit)
    //设置初始值
    keyboard && keyboard.setInput('')
    inputVal.value = ''
}
watch(() => props.modelValue, (newVal) => {
    visible.value = newVal
    if (!newVal) {
        keyboard && keyboard.clearInput()
        inputVal.value = ''
        isInit = false
    }

})
watch(() => visible.value, (newVal) => {
    emit('update:modelValue', newVal)
})


const onKeyPress = (button) => {
    let input = keyboard.getInput()
    if (button === '{clear}') {//清空
        keyboard.setInput('')
    }
    if (button === '{zf}') {//正负号
        if (!input || input === '0') return  //如果没有值或0 则直接返回
        if (input.indexOf('-') != -1) { //如果为负值
            keyboard.setInput(input.split('-')[1])
        } else {
            keyboard.setInput('-' + input)
        }
    }
    if (button === '{confirm}') {//确认
        emit('update:modelValue', false)
    }
    emit('onKeyPress', button)
}
const onChange = (input) => {
    //console.log(input)
    let filterInput
    //以小数点开头 直接去掉
    if (input.startsWith('.')) {
        filterInput = input.slice(0, -1)
        console.log(filterInput)
    } else {
        if (input.includes('.')) {
            // 确保只有一个小数点
            filterInput = input.split('.')[0] + '.' + input.split('.')[1]

        } else {
            //以0开头并且超过两位 而且不包含小数点，则去掉首位0
            if (input.length >= 2 && input.startsWith('0')) {
                filterInput = input.slice(1)
            } else {
                filterInput = input
            }


        }
    }
    inputVal.value = filterInput
    keyboard.setInput(filterInput)
    emit('onChange', filterInput)

}

//确定
function confirmInput() {
    //如果以.结尾 则去掉.
    let input = keyboard.getInput()
    if (input.endsWith('.')) {
        input = input.slice(0, -1)
    }

    if (input === '') {
        ElMessage({
            message: props.placeholder,
            type: 'warning',
        })
        return
    }


    emit('onConfirm', input)

}


//组件解绑之前 销毁keyboard实例，避免内存泄漏
onBeforeUnmount(() => {
    // console.log('onBeforeUnmount')
    if (keyboard) {
        keyboard.destroy();
        keyboard = null
    }
})

//初始化keyboard
function initKeyboard(isInit) {
    const layout = props.layout
    let defaultLayout = [
        '1 2 3',
        '4 5 6',
        '7 8 9',
        '. 0 {bksp}',
        // '{clear} {confirm}'

    ]
    if (!props.isShowPoint) { //不显示小数点
        defaultLayout = [
            '1 2 3',
            '4 5 6',
            '7 8 9',
            '0 {bksp}',
        ]
    }
    if (layout) {
        defaultLayout = layout
    }

    // console.log(defaultLayout)
    const options = {
        onChange,
        onKeyPress,
        layout: {
            default: defaultLayout,
        },
        display: {
            '{bksp}': '⌫',
            '{zf}': '+/-'
        },


    }
    if (isInit) {
        keyboard = new Keyboard(`${props.keyboardContainerClass}`, options)

    } else {
        keyboard.setOptions(options)
    }


}





</script>

<style lang='scss' scoped>
:deep(.count-keyboard-dialog) {
    // position: absolute !important;
    // // right: 13px !important;
    // top: 20px;
    // margin: 0 !important;
    // --el-dialog-width: calc(70% - 25px);
}

#count-keyboard {
    min-height: 269px;

    :deep(.hg-button-bksp) {
        width: 20px;
        font-weight: bold !important;
    }

    :deep(.hg-rows) {
        height: 100%;

        .hg-row {
            height: 19%;
            box-sizing: border-box;
        }
    }

    :deep(.hg-button-confirm) {
        min-width: 30%;

        font-weight: bold !important;
        color: #fff;
        background-color: var(--el-color-primary);
    }

    :deep(.hg-button) {
        padding: 20px 5px;
        font-size: 20px;
        height: 100%;
        line-height: 1;
        box-sizing: border-box;
        flex: 1;
    }

}

.flex {
    display: flex;

    &>div {
        flex: 1;
    }

}

//不显示小数点的最后两行按钮布局

div[data-class="nopoint"] {
    :deep(div[data-skbtn="0"]) {
        width: 66.6666%;

    }

    :deep(div[data-skbtn="{bksp}"]) {
        width: 33.3333% !important;
    }
}
</style>
